package com.example.sunmiv1.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.StoreOrderAdapter;
import com.example.sunmiv1.entity.CashierListInfo;
import com.example.sunmiv1.entity.StoreOrderInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class StoreOrderActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.tvSearch_storeOrder)
    TextView tvSearchStoreOrder;
    @BindView(R.id.edit_storeOrder)
    EditText editStoreOrder;
    @BindView(R.id.orderType_storeOrder)
    Spinner orderTypeStoreOrder;
    @BindView(R.id.from_storeOrder)
    Spinner fromStoreOrder;
    @BindView(R.id.payType_storeOrder)
    Spinner payTypeStoreOrder;
    @BindView(R.id.people_storeOrder)
    Spinner peopleStoreOrder;
    @BindView(R.id.listView_storeOrder)
    PullToRefreshListView listViewStoreOrder;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;


    private int page = 1;
    private Context context;
    private ACache aCache;
    private LoadingDialog loadingDialog;
    private CashierListInfo cashierListInfo;

    private List<String> orderType = new ArrayList<>();//訂單類型
    private List<String> fromType = new ArrayList<>();//訂單來源
    private List<String> payType = new ArrayList<>();//支付方式
    private List<String> cashierNameList = new ArrayList<>();//收銀員名稱集合
    private List<CashierListInfo.DataBean> cashierList = new ArrayList<>();//收銀員集合

    private int orderTypeFLag = 0;//訂單類型
    private int fromTypeFlag = 0;//訂單來源
    private int payTypeFlag = 0;//支付方式
    private String cashierId = "";//收銀員id

    private boolean order = false;
    private boolean from = false;
    private boolean pay = false;
    private boolean cashier = false;

    private StoreOrderInfo storeOrderInfo;
    private StoreOrderAdapter storeOrderAdapter;
    private List<StoreOrderInfo.DataBean> storeOrderList = new ArrayList<>();

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    cashierList.add(new CashierListInfo.DataBean("", "全部"));
                    cashierNameList.add("全部收銀員");
                    for (CashierListInfo.DataBean dataBean : cashierListInfo.getData()) {
                        cashierList.add(dataBean);
                        cashierNameList.add(dataBean.getName());
                    }
                    setCashierList();
                    break;
                case 2:
                    cashierList.add(new CashierListInfo.DataBean("", "全部"));
                    cashierNameList.add("全部收銀員");
                    setCashierList();
                    break;
                case 3:
                    for (StoreOrderInfo.DataBean dataBean : storeOrderInfo.getData()) {
                        storeOrderList.add(dataBean);
                    }
                    page++;
                    setStoreOrderAdapter();
                    break;
                case 4:
                    setStoreOrderAdapter();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_store_order);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.sotreOrderTitle);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        initData();
        initListener();
    }

    private void initData() {
        orderType.add(getString(R.string.sotreOrderOrder1));
        orderType.add(getString(R.string.sotreOrderOrder2));
        orderType.add(getString(R.string.sotreOrderOrder3));
        setOrderType();
        fromType.add(getString(R.string.sotreOrderFrom1));
        fromType.add(getString(R.string.sotreOrderFrom2));
        fromType.add(getString(R.string.sotreOrderFrom3));
        setFromType();
        payType.add(getString(R.string.sotreOrderPay1));
        payType.add(getString(R.string.sotreOrderPay2));
        payType.add(getString(R.string.sotreOrderPay3));
        payType.add(getString(R.string.sotreOrderPay4));
        payType.add(getString(R.string.sotreOrderPay5));
        payType.add(getString(R.string.sotreOrderPay6));
        payType.add(getString(R.string.sotreOrderPay7));
        payType.add(getString(R.string.sotreOrderPay8));
        setPayType();
    }

    /*設置訂單類型*/
    private void setOrderType() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, orderType);
        arrayAdapter.setDropDownViewResource(R.layout.item_drops);
        orderTypeStoreOrder.setAdapter(arrayAdapter);
    }

    /*設置訂單來源*/
    private void setFromType() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, fromType);
        arrayAdapter.setDropDownViewResource(R.layout.item_drops);
        fromStoreOrder.setAdapter(arrayAdapter);
    }

    /*設置支付方式*/
    private void setPayType() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, payType);
        arrayAdapter.setDropDownViewResource(R.layout.item_drops);
        payTypeStoreOrder.setAdapter(arrayAdapter);
    }

    /*設置支付方式*/
    private void setCashierList() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, cashierNameList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drops);
        peopleStoreOrder.setAdapter(arrayAdapter);
    }

    private void setStoreOrderAdapter() {
        if (storeOrderAdapter == null) {
            storeOrderAdapter = new StoreOrderAdapter(context, storeOrderList);
            listViewStoreOrder.setAdapter(storeOrderAdapter);
        } else {
            storeOrderAdapter.notifyDataSetChanged();
        }
    }

    private void initListener() {
        listViewStoreOrder.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                storeOrderList.clear();
                setStoreOrderAdapter();
                getOrder();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getOrder();
            }
        });
        orderTypeStoreOrder.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (!order) {
                    order = true;
                    return;
                }
                orderTypeFLag = position;
                page = 1;
                storeOrderList.clear();
                setStoreOrderAdapter();
                getOrder();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        fromStoreOrder.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (!from) {
                    from = true;
                    return;
                }
                fromTypeFlag = position;
                page = 1;
                storeOrderList.clear();
                setStoreOrderAdapter();
                getOrder();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        payTypeStoreOrder.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (!pay) {
                    pay = true;
                    return;
                }
                payTypeFlag = position;
                page = 1;
                storeOrderList.clear();
                setStoreOrderAdapter();
                getOrder();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        peopleStoreOrder.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (!cashier) {
                    cashier = true;
                    return;
                }
                cashierId = cashierList.get(position).getId();
                page = 1;
                storeOrderList.clear();
                setStoreOrderAdapter();
                getOrder();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        getCashier();
        getOrder();
    }

    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
        Intent intent = new Intent(context, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != 1 && requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {//掃描結果回調
            Bundle bundle = data.getExtras();
            page = 1;
            storeOrderList.clear();
            setStoreOrderAdapter();
            editStoreOrder.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
            getOrder();
        }
    }

    @OnClick({R.id.title_back, R.id.tv_start_time,R.id.btn_to_top, R.id.tv_end_time, R.id.tvSearch_storeOrder,R.id.scan_storeOrder})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.tv_start_time:
                Tools.getDateFromDatePickerDialog(tvStartTime);
                break;
            case R.id.tv_end_time:
                Tools.getDateFromDatePickerDialog(tvEndTime);
                break;
            case R.id.tvSearch_storeOrder:
                page = 1;
                storeOrderList.clear();
                setStoreOrderAdapter();
                getOrder();
                break;
            case R.id.scan_storeOrder:
                startQrCode();
                break;
            case R.id.btn_to_top:
                listViewStoreOrder.getRefreshableView().setSelection(0);
                break;
        }
    }

    private void getCashier() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            HttpUtils.post(context, Common.GET_CASHIER, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    cashierListInfo = GsonUtils.JsonToBean(text, CashierListInfo.class);
                    Message msg = new Message();
                    if (cashierListInfo.getStatus() == 1) {
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /*獲取門店經營訂單*/
    private void getOrder() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("order_no", editStoreOrder.getText().toString().trim());
            jsonObject.put("cashier_id", cashierId);
            jsonObject.put("start_time", tvStartTime.getText().toString().trim());
            jsonObject.put("end_time", tvEndTime.getText().toString().trim());
            jsonObject.put("pay_type", payTypeFlag);
            jsonObject.put("order_type", orderTypeFLag);
            jsonObject.put("type", fromTypeFlag);
            jsonObject.put("page", page);
            jsonObject.put("limit", 20);
            HttpUtils.post(context, Common.GET_STORE_ORDER, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    listViewStoreOrder.onRefreshComplete();
                    storeOrderInfo = GsonUtils.JsonToBean(text, StoreOrderInfo.class);
                    Message msg = new Message();
                    if (storeOrderInfo.getStatus() == 1) {
                        msg.what = 3;
                    } else {
                        msg.what = 4;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    listViewStoreOrder.onRefreshComplete();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否則所有的組件都不會有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);

    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //獲取輸入框當前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 點擊的是輸入框區域，保留點擊EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}
